<?php
namespace app\index\controller;
use think\Db;
use think\request;
use think\Controller;


class Payment extends Controller {

	//网商采宝回调处理
	public function callback() {
		$status=input("orderStatus");
		$sn=input("appOrderNo");
		file_put_contents("log2.txt", $sn."----".$status.now_time().PHP_EOL, FILE_APPEND);
		if($status=="PAY_SUC"){
			//file_put_contents("log.txt", $sn."----".now_time().PHP_EOL, FILE_APPEND);
			$pay_info = db('paylog')->where('order_sn',$sn)->find();
			if($pay_info['state'] ==1){
				$type=$pay_info['type'];
				if($type==1){//购卡
					$this->call_czlevel($pay_info,input('receiveAmount'));
				}elseif($type==2){//充值
					$this->call_fill($pay_info,input('receiveAmount'));
				}elseif($type==3){//客房预订
					$this->call_reserve($pay_info,input('receiveAmount'));
				}elseif($type==8){//桌面收银扫一扫
					$this->call_worksys($pay_info,input('receiveAmount'));
				}elseif($type==7){
					$this->call_reserve_ct($pay_info,input('receiveAmount'));
				}
				
			}else{
				return "success";
				echo '请勿重复付款';
			}
		}
		return "success";
	}
	public function test($sn){
			$pay_info = db('paylog')->where('order_sn',$sn)->find();
			if($pay_info['state'] ==1){
				$type=$pay_info['type'];
				if($type==1){//
					$this->call_czlevel($pay_info,input('receiveAmount'));
				}
				
			}else{
				return "success";
				echo '请勿重复付款';
			}
	}
	//购买会员卡
	public function call_czlevel($paylog,$receiveAmount){
	    if(bccomp($paylog['balance'], $receiveAmount, 2) != 0){
			//echo '数据异常';exit;
		}
		Db::startTrans();
		$res=[];
		
		//查询出这个会员是否有推荐业务员
		$tj_emp = db('user')->where('id',$paylog['user_id'])->value('tj_emp'); 
		if($tj_emp != 0){ 
			$role_id = db('emp')->where('user_id',$tj_emp)->value('role_name_id');
			if($role_id){
				//查询出这个业务员的分佣比例
			    $commission = db('admin_cate')->where('id',$role_id)->value('commission'); 
			}else{
				$commission = 5;
			} 
			//业务员所得分佣
			$yj = round($paylog['balance']*($commission/100),2);
			$data['yj']=['inc',$yj];
			$res[]=db('user')->where('id',$tj_emp)->update($data);
			//添加分佣日志
		    $res[] = add_commission($tj_emp,$yj,$paylog['user_id'],$paylog['level_id'],$paylog['balance'],'推荐会员购卡',1);
		} 
		
		//查询出用户购买这个等级所有赠送的房券总数
		$zs_num=db("userlevel")->where('id',$paylog['level_id'])->value('zs_num'); 
		$up['kaquan']=['inc',$zs_num];
		$up['balance']=['inc',$paylog['balance']];
		$up['total_chongzhi']=['inc',$paylog['balance']];
		$up['total_count']=['inc',1];
		$up['level_id']=$paylog['level_id'];
		$up['start_time']=now_time();
		$res[]=db('user')->where('id',$paylog['user_id'])->update($up);
		$res[]=db('paylog')->where('id',$paylog['id'])->update(['state'=>2,'pay_time'=>now_time()]);
		//增加用户客房关系
		$res[]=$this->add_userhouse($paylog['level_id'],$paylog['user_id'],$paylog['staff_id'],$paylog['store_id'],$paylog['balance']);
		//增加充值记录
		$res[]=consume_log($paylog['order_sn'],$paylog['user_id'],$paylog['store_id'],$paylog['balance'],$paylog['level_id'],$paylog['pay_type'],$paylog['level_id'],now_time(),1,$paylog['staff_id'],'购买会员卡');
		if (in_array(false, $res)){
		    Db::rollback();
		}else {
		    Db::commit();
		}
	}
	//增加用户客房关系
	public function add_userhouse($leve_id,$user_id,$staff_id,$store_id,$balance){
		$houses=db("levelitem")->where('level_id',$leve_id)->where("type",1)->select();
		//即时赠送
		if($houses){
			$start_time=now_time();
			$end_time=date('Y-m-d H:i:s', strtotime("+1 year"));
			foreach($houses as $i){
				$items[]=array('type'=>1,'user_id'=>$user_id,'house_id'=>$i['house_id'],"num"=>$i['num'],"start_time"=>$start_time,"end_time"=>$end_time);
			}
		}
		//后续赠送
		$hx_zs=db("levelitem")->where('level_id',$leve_id)->where("type",2)->select();
		if($hx_zs){
			$levle=db('userlevel')->where("id",$leve_id)->find();
			$year=$levle['zs_date'];
			for($i=1;$i<=$year;$i++){
				$start_time=date('Y-m-d H:i:s', strtotime("+1 year"));
				$end=$i++;
				$end_time=date('Y-m-d H:i:s', strtotime("+$end year"));
				foreach($hx_zs as $i){
					$items[]=array('type'=>2,'user_id'=>$user_id,'house_id'=>$i['house_id'],"num"=>$i['num'],"start_time"=>$start_time,"end_time"=>$end_time);
				}
			}
		}
		if(isset($items)){
			db('userhouse')->insertAll($items);
			$r=db('userhouse')->getLastInsID();
			$r1=db('userhouse')->max('id');
			$order_sn = order_create_no();
			$time=now_time();
			$num = db('userlevel')->where('id',$leve_id)->field('zs_num')->find();
			//添加赠送记录
			for ($x=$r; $x<=$r1; $x++) {
				$info = db('userhouse')->where('id',$x)->find();
				fq_log(3,$order_sn,$user_id,$x,$info['num'],$time,'购买会员卡赠送',$num['zs_num'],$info['type'],$store_id,$balance,$leve_id,$staff_id);
			}
		}
		return true;	
	}
	//充值
	public function call_fill($paylog,$receiveAmount){
	    if(bccomp($paylog['balance'], $receiveAmount, 2) != 0){
			//echo '数据异常';exit;
		}
		Db::startTrans();
		$res=[];
		$kj = db('fill')->where('id',$paylog['level_id'])->value('balance');
		$up['balance']=['inc',$kj];
		$up['total_chongzhi']=['inc',$paylog['balance']];
		$up['total_count']=['inc',1];
		$res[]=db('user')->where('id',$paylog['user_id'])->update($up);
		$res[]=consume_log($paylog['order_sn'],$paylog['user_id'],0,$paylog['balance'],$paylog['level_id'],$paylog['pay_type'],0,now_time(),1,0,'会员充值');
		$res[]=db('paylog')->where('id',$paylog['id'])->update(['state'=>2,'pay_time'=>now_time()]);
		if (in_array(false, $res)){
		    Db::rollback();
		}else {
		    Db::commit();
		}
	}
	public function pay_success(){
		//获取订单信息
    	$paylog = db('paylog')->alias('p')
		->join('userlevel u','p.level_id = u.id','LEFT')
    	->where('p.order_sn',input('order_sn'))
		->field('p.*,u.name')
    	->find();
		$this->assign('paylog',$paylog);
		return $this->fetch();
	}
	//商户进件回调
	public function qy_callback(){
		$status=input("sign_status");
		$cb_merchant_code=input("cb_merchant_code");
		file_put_contents("qy.txt", '采宝商户号：'.$cb_merchant_code.'，省钱啦商户号：'.input('merchant_code')."----".$status.now_time().PHP_EOL, FILE_APPEND);
		if($status=="SUCCESS"){
			$pay_info = db('agent_qianyue')->where('merchants',$cb_merchant_code)->field("state")->find();
			if($pay_info['state'] ==2){ //审核中
				$agentlog = new App();
				$agentlog->qy_agent($cb_merchant_code,input('merchant_code'));
			}else{
				return "success";
			}
		}else{
			db('agent_qianyue')->where('merchants',$cb_merchant_code)->update(['reason'=>input('reject_reason'),'state'=>3]);
		}
		return "success";
	}
	public function  paytest($sn){
		$log=db('paylog')->where("order_sn")->find();
		$this->call_reserve_ct($log, 2);
	}
	//餐厅预订
	public function call_reserve_ct($paylog,$receiveAmount){
	    if(bccomp($paylog['balance'], $receiveAmount, 2) != 0){
			//echo '数据异常';exit;
		}
		Db::startTrans();
		$res=[];
		$res[]=db('reserve_ct')->where('order_id',$paylog['room_id'])->update(['state'=>2,'pay_time'=>now_time()]);  //更新预定表
		$res[]=db('paylog')->where('id',$paylog['id'])->update(['state'=>2,'pay_time'=>now_time()]);//更新支付表
		if (in_array(false, $res)){
		    Db::rollback();
		}else {
		    Db::commit();
		}
	}
	//客房预订
	public function call_reserve($paylog,$receiveAmount){
	    if(bccomp($paylog['balance'], $receiveAmount, 2) != 0){
			//echo '数据异常';exit;
		}
		Db::startTrans();
		$res=[];
		$room_num = db('reserve')->where('order_id',$paylog['id'])->value('room_num');
		$res[]= db('room_sort')->where('id',$paylog['room_id'])->setDec('room_num',$room_num);
		$res[]=db('reserve')->where('order_id',$paylog['id'])->update(['state'=>2,'pay_time'=>now_time()]);  //更新预定表
		$res[]=db('paylog')->where('id',$paylog['id'])->update(['state'=>2,'pay_time'=>now_time()]);//更新支付表
		if (in_array(false, $res)){
		    Db::rollback();
		}else {
		    Db::commit();
		}
	}
	
	//桌面收银扫一扫
	public function call_worksys($paylog,$receiveAmount){
		Db::startTrans();
		$res=[];
		$res[]=db('paylog')->where('id',$paylog['id'])->update(['state'=>2,'pay_time'=>now_time()]);//更新支付表
		if (in_array(false, $res)){
		    Db::rollback();
		}else {
		    Db::commit();
		}
	}
}
